package com.voice.client;

import com.alibaba.fastjson.JSONObject;
import com.voice.client.auth.AuthHandler;
import com.voice.client.auth.AuthenticationFactory;
import com.voice.client.message.StreamClient;
import com.voice.client.message.StreamClientFactory;
import com.voice.client.message.callback.MessageCallback;
import com.voice.core.entity.HttpHeader;
import com.voice.core.channel.tcp.impl.IOSelectorConnectionManager;
import com.voice.core.connection.Connection;
import com.voice.core.connection.ConnectionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;
import java.net.InetSocketAddress;


//@SpringBootApplication
@Slf4j
public class VoiceClientApplication1 {

    public static void main1(String[] args) throws IOException {
        //SpringApplication.run(VoiceClientApplication.class, args);
        Profile profile = Profile.getDeviceProfile("http://47.103.205.167:8081", "123456789","HySgN9HBphQv212uwTk5yUfVFICu00Ik", "BaEViyPS3WvL5HAXmNP6xw5V2tYKIIoF");
        ConnectionManager connectionManager=new IOSelectorConnectionManager();
        Connection connection=connectionManager.connect(new InetSocketAddress(profile.getHost(),profile.getPort()));
        stream(connection,profile);

        StreamClient streamClient = StreamClientFactory.streamClient(profile);
        streamClient.connect(message -> {
            log.info("{}",message);
            if (message.getTopic().equals("/device/third/server")) {
                JSONObject jsonObject = JSONObject.parseObject(new String(message.getPayload()));
                String host = jsonObject.getString("host");
                Integer port = jsonObject.getInteger("port");
                try {
                    Connection newConnection=connectionManager.connect(new InetSocketAddress(host,port));
                    stream(newConnection,profile);
                    connection.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            } else {
                System.out.println(message);
            }
            return MessageCallback.Action.CommitSuccess;
        });
        while (true){
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void stream( Connection connection,Profile profile) throws IOException {
        HttpHeader headers = new HttpHeader();
        AuthHandler authHandler = AuthenticationFactory.getAuthHandler(profile);
        authHandler.getAuthParams().forEach((key,value)->headers.put(key,value));
        headers.path("/device/controller/echo/success");
        connection.writeHeaders(headers.toString().getBytes(),true,null).whenComplete((t,f)->{
            if(f==null){
                connection.writeStream(System.in);
            }
        });
    }
}
